package com.xzit.rental.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xzit.rental.entity.User;
import com.xzit.rental.entity.UserRole;
import com.xzit.rental.mapper.UserMapper;
import com.xzit.rental.mapper.UserRoleMapper;
import com.xzit.rental.service.IOssService;
import com.xzit.rental.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xzit.rental.utils.Result;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import java.util.Arrays;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 何时说晚安
 * @since 2024-12-05
 */
@Service
@Transactional
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Resource
    private UserMapper userMapper;
    @Resource
    private IOssService ossService;
    @Resource
    private UserRoleMapper userRoleMapper;

    @Override
    public User selectByUsername(String username) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username);
        return userMapper.selectOne(wrapper);
    }

    @Override
    public List<String> selectRoleName(int id) {
        return userMapper.selectRoleNamesByUserId(id);
    }

    @Override
    public Page<User> searchByPage(Page<User> page, User user) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        if(user.getDeptId()!=null && user.getDeptId()==0){
            return baseMapper.selectPage(page,null);
        }
        wrapper.eq(ObjectUtil.isNotEmpty(user.getDeptId()),"dept_id",user.getDeptId());
        wrapper.like(StrUtil.isNotBlank(user.getUsername()),"username",user.getUsername());
        wrapper.like(StrUtil.isNotBlank(user.getRealname()),"realname",user.getRealname());
        wrapper.like(StrUtil.isNotBlank(user.getNickname()),"nickname",user.getNickname());
        wrapper.like(StrUtil.isNotEmpty(user.getPnone()),"pnone",user.getPnone());
        wrapper.like(StrUtil.isNotBlank(user.getEmail()),"email",user.getEmail());
        return userMapper.selectPage(page,wrapper);

    }

    @Override
    public boolean delete(String ids) {
        List<Integer> list = Arrays.stream(ids.split(","))
                .map(Integer::parseInt).toList();
        try{
            if(list.size()>0){
                for (Integer id : list) {
                    User user = baseMapper.selectById(id);
                    // 判断用户是否是超级管理员
                    if(user.getIsAdmin()!=null && user.getIsAdmin()!=1){
                        // 删除用户头像
                        if(user.getAvatar()!=null && user.getAvatar().length()>0){
                            ossService.delete(user.getAvatar());
                        }
                        // 删除用户
                        baseMapper.deleteById(id);
                        // 删除用户和角色关联表的数据
                        userRoleMapper.delete(new QueryWrapper<UserRole>().eq("user_id",id));
                    }
                }
            }
            return true;
        }catch (Exception e){
            throw new RuntimeException("删除用户失败！");
        }
    }

    @Override
    public boolean bindRole(int userId, List<Integer> list) {
        // 先删除当前用户与角色的关联
        userRoleMapper.delete(new QueryWrapper<UserRole>().eq("user_id",userId));
        // 重新插入用户与角色关联
        if(list.size()>0){
            for (Integer roleId : list) {
                UserRole userRole = new UserRole();
                userRole.setUserId(userId);
                userRole.setRoleId(roleId);
                userRoleMapper.insert(userRole);
            }
            return true;
        }
        return false;
    }

}
